//获取token
var token = CoreUtil.getData("access_token");
//地址栏转义token中的#号
var tokenQuery = token.replace("#", "%23");
var tableIns1;
var table = layui.table;
var form = layui.form;
var layer = layui.layer;
var $ = jQuery = layui.jquery;
var laydate = layui.laydate;

var carousel = layui.carousel;
var upload = layui.upload;
var uploadInst;
var carousels;
layui.use(['table', 'layer', 'laydate', 'upload', 'carousel'], function () {

    //加载table
    tableIns1 = table.render({
        elem: '#showTable'
        , contentType: 'application/json'
        , headers: {"authorization": token}
        , page: false //开启分页
        , url: '/sysBanner/listByPage' //数据接口
        , method: 'POST'
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
            }
        }
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'id'},
                {
                    field: 'fileId', title: '图片', hide:true
                    , templet: function (item) {
                        var html = '<img src="' + '/sysFile/imageshow/' + item.fileId + '?authorization=' + tokenQuery + '" width="600" height="280" style="max-width:600px !important ;height:280px"/>'
                        return html;
                    }
                    , hide: true
                },
                {field: 'title', title: '图片标题', hide: true},
                {width: 80, field: 'sortr', title: '排序', sort: true, hide:true},
                {width: 180, field: 'createTime', title: '创建时间'},
                {width: 200, toolbar: "#tool", title: '操作'}
            ]
        ]
        , toolbar: '#toolbar'
        , done: function (res, curr, count) {
            if (count > 0) {
                var data = res.data;
                show_banner(data);
            }
        }
    });


    //表头工具
    table.on('toolbar(showTable)', function (obj) {
        switch (obj.event) {
            case 'batchDeleted':
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                if (data.length == 0) {
                    layer.msg("请选择要批量删除的列");
                } else {
                    var ids = [];
                    $(data).each(function (index, item) {
                        ids.push(item.id);
                    });
                    tipDialog(ids);
                }
                break;
            case 'add':
                $(".table_div").hide();
                $(".operation").show();

                $(".title").html("新增");
                $(".operation input[name=id]").val("");
                $(".operation input[name=deptId]").val("");
                $(".operation input[name=fileId]").val("");
                $(".operation input[name=title]").val("");
                $(".operation input[name=sortr]").val("");
                $(".operation input[name=createTime]").val("");

                upload_reload();
                break;
        }
        ;
    });
    //列操作
    table.on('tool(showTable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'del':
                var ids = [];
                ids.push(data.id);
                tipDialog(ids);
                break;
            case 'edit':
                $(".table_div").hide();
                $(".operation").show();
                $(".title").html("编辑");
                $(".operation input[name=id]").val(data.id);
                $(".operation input[name=fileId]").val(data.fileId);
                $(".operation input[name=title]").val(data.title);
                $(".operation input[name=sortr]").val(data.sortr);
                $(".operation input[name=createTime]").val(data.createTime);

                // 显示图片
                show_img("/sysFile/imageshow/" + data.fileId + "?authorization=" + tokenQuery);
                break;
            case 'show':
                var img = new Image();
                img.src = '/sysFile/imageshow/' + data.fileId + '?authorization=' + tokenQuery;
                img.onload = function () {

                    var height = img.height;
                    var width = img.width;
                    var scaleWH = width / height;
                    var bigH = 600;
                    var bigW = scaleWH * bigH;
                    if (bigW > 900) {
                        bigW = 900;
                        bigH = bigW / scaleWH;
                    }

                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        shadeClose: true,
                        area: [bigW + 'px', bigH + 'px'], //宽高
                        content: '<img width=bigW height=bigH src="' + img.src + '" />'
                    });
                }
                break;

        }
    });

    //导出
    $('#export').on('click', function () {
        //原先分页limit
        var exportParams = {
            limit: 10000,
            key: $("#key").val()
        };
        CoreUtil.sendPost("/sysBanner/listByPage", exportParams, function (res) {
            //初始化渲染数据
            if (res.data != null && res.data.records != null) {
                table.exportFile(tableIns1.config.id, res.data.records, 'xls');
            }
        });
    });

    //删除
    var tipDialog = function (ids) {
        layer.open({
            content: "确定要删除么?",
            yes: function (index, layero) {
                layer.close(index); //如果设定了yes回调，需进行手工关闭
                CoreUtil.sendDelete("/sysBanner/delete", ids, function (res) {
                    layer.msg(res.msg, {time: 1000}, function () {
                        search();
                    });
                });
            }
        });
    };

    //返回
    $("#btn_cancel").click(function () {
        $(".table_div").show();
        $(".operation").hide();
        return false;
    });

    //监听保存
    form.on('submit(submit)', function (data) {
        if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
            CoreUtil.sendPost("/sysBanner/add", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        } else {
            CoreUtil.sendPut("/sysBanner/update", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        }

        return false;
    });
    //普通图片上传
    uploadInst = upload.render({
        elem: '#test1'
        , url: '/sysFile/uploadImg' //改成您自己的上传接口
        , headers: {"authorization": token}
        , acceptMime: 'image/*'
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                show_img(result)
                // $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            console.log("上传返回结果 ：： ", res)
            //如果上传失败
            if (res.code != 0) {
                upload_error();
                return layer.msg(res.msg);
            }
            //上传成功
            var data = res.data;
            $(".operation input[name=fileId]").val(data.id);

            $('#demoText').html()
        }
        , error: function () {
            upload_error();
        }
    });
    var show_img = function (src) {
        var html = '<img class="layui-upload-img" src="' + src + '">';
        $('#demo1').html(html);
    }

    var show_banner = function (banner_date) {
        var ids = [];
        $(banner_date).each(function (index, item) {
            ids.push(item.fileId);
        });
        var html;
        // 请求获取图片地址
        CoreUtil.sendPost("/sysFile/details", ids, function (res) {
            var data = res.data;
            for (var i = 0; i < banner_date.length; i++) {
                var banner = banner_date[i];
                for (var j = 0; j < data.length; j++) {
                    var data1 = data[j];
                    if (banner.fileId == data1.id) {
                        html += '' +
                            '<div>' +
                            '<p class="banner_title">' + banner.title + '</p>' +
                            '<img src="' + data1.url + '" style="width: 100%; height: 100%;">' +
                            '</div>';
                        continue;
                    }
                }
            }
            $('#banner-item').html(html);
            carousels.reload();
        });
    }
    var upload_error = function () {
        //演示失败状态，并实现重传
        var demoText = $('#demoText');
        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
        demoText.find('.demo-reload').on('click', function () {
            uploadInst.upload();
        });
    }
    carousels = carousel.render({
        elem: '#carousel'
        , width: '600px'
        , height: '280px'
        , anim: 'default'
        , autoplay: true
        , interval: 3000
        , index: 0
        , arrow: 'hover'
        , indicator: 'inside'

    });
});

function upload_reload() {
    uploadInst.reload();
    $('#demo1').html(""); //图片链接（base64）
    $('#demoText').html() //
}

//执行查询
function search() {
    //这里以搜索为例
    tableIns1.reload({
        where: { //设定异步数据接口的额外参数，任意设
            key: $("#key").val()
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }
    });
    // carousel.reload();
};